package com.gd.deron.smartrobot.baobao.hci;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.sinovoice.hcicloudsdk.android.tts.player.TTSPlayer;
import com.sinovoice.hcicloudsdk.api.tts.HciCloudTts;
import com.sinovoice.hcicloudsdk.common.HciErrorCode;
import com.sinovoice.hcicloudsdk.common.Session;
import com.sinovoice.hcicloudsdk.common.asr.AsrInitParam;
import com.sinovoice.hcicloudsdk.common.tts.ITtsSynthCallback;
import com.sinovoice.hcicloudsdk.common.tts.TtsConfig;
import com.sinovoice.hcicloudsdk.common.tts.TtsInitParam;
import com.sinovoice.hcicloudsdk.common.tts.TtsSynthResult;
import com.sinovoice.hcicloudsdk.player.TTSCommonPlayer;
import com.sinovoice.hcicloudsdk.player.TTSPlayerListener;
import com.sinovoice.hcicloudsdk.player.TTSCommonPlayer.PlayerEvent;

public class HciCloudTtsHelper {
    private static final String TAG = HciCloudTtsHelper.class.getSimpleName();

    private static HciCloudTtsHelper mInstance;
    private String mCapKey;
    private static Handler mUIHandle = null;

    private TtsConfig mTtsConfig = null;
    private TTSPlayer mTtsPlayer = null;

    private HciCloudTtsHelper() {
    }

    public static HciCloudTtsHelper getInstance() {
        if (mInstance == null) {
            mInstance = new HciCloudTtsHelper();
        }
        return mInstance;
    }

    /**
     * Tts引擎初始化 辅助工具 : TtsInitParam:该类的实例通过addParam(key, value)的方式添加Tts初始化的参数,
     * 再通过getStringConfig() 获取初始化时需要的字符串参数 config 初始化方法:
     * HciCloudTts.hciTtsInit(config)
     */
    public boolean init(Context context, Handler handle,String strWelcome) {
        mCapKey = AccountInfo.getInstance().getTtsCapKey();
        mUIHandle = handle;

        // 构造Tts初始化的帮助类的实例
        TtsInitParam ttsInitParam = new TtsInitParam();

        // 获取App应用中的lib的路径,放置能力所需资源文件。如果使用/data/data/packagename/lib目录,需要添加android_so的标记
        String dataPath = context.getFilesDir().getAbsolutePath().replace("files", "lib");
        ttsInitParam.addParam(TtsInitParam.PARAM_KEY_DATA_PATH, dataPath);        
        ttsInitParam.addParam(TtsInitParam.PARAM_KEY_FILE_FLAG, "android_so");

        // 此处演示初始化的能力为tts.cloud.xiaokun, 用户可以根据自己可用的能力进行设置, 另外,此处可以传入多个能力值,并用;隔开
        // 如 "tts.cloud.xiaokun;tts.cloud.zhangNan;tts.local.xiaoKun"
        ttsInitParam.addParam(AsrInitParam.PARAM_KEY_INIT_CAP_KEYS, mCapKey);          
        
        // 配置播放器的属性。包括：音频格式，音库文件，语音风格，语速等等。详情见文档。
     	mTtsConfig = new TtsConfig();
     	
     	// 音频格式
     	mTtsConfig.addParam(TtsConfig.BasicConfig.PARAM_KEY_AUDIO_FORMAT, "pcm16k16bit");
     	// 指定语音合成的能力
     	mTtsConfig.addParam(TtsConfig.SessionConfig.PARAM_KEY_CAP_KEY, mCapKey);
     	// 设置合成语速
     	mTtsConfig.addParam(TtsConfig.BasicConfig.PARAM_KEY_SPEED, "5");

        mTtsPlayer = new TTSPlayer();        
        
     	mTtsPlayer.init(ttsInitParam.getStringConfig(), new TTSEventProcess());

     	if (mTtsPlayer.getPlayerState() == TTSPlayer.PLAYER_STATE_IDLE) {
     		Log.i(TAG, "TTS init success");     	
     		if(null != strWelcome) {
     			mTtsPlayer.play(strWelcome, mTtsConfig.getStringConfig());
     		}
     		return true;
     	} else {
     		return false;
     	}     	
    }
    public boolean init(Context context) {
        mCapKey = AccountInfo.getInstance().getTtsCapKey();

        // 构造Tts初始化的帮助类的实例
        TtsInitParam ttsInitParam = new TtsInitParam();

        // 获取App应用中的lib的路径,放置能力所需资源文件。如果使用/data/data/packagename/lib目录,需要添加android_so的标记
        String dataPath = context.getFilesDir().getAbsolutePath().replace("files", "lib");
        ttsInitParam.addParam(TtsInitParam.PARAM_KEY_DATA_PATH, dataPath);        
        ttsInitParam.addParam(TtsInitParam.PARAM_KEY_FILE_FLAG, "android_so");

        // 此处演示初始化的能力为tts.cloud.xiaokun, 用户可以根据自己可用的能力进行设置, 另外,此处可以传入多个能力值,并用;隔开
        // 如 "tts.cloud.xiaokun;tts.cloud.zhangNan;tts.local.xiaoKun"
        ttsInitParam.addParam(AsrInitParam.PARAM_KEY_INIT_CAP_KEYS, mCapKey);          
        
        // 配置播放器的属性。包括：音频格式，音库文件，语音风格，语速等等。详情见文档。
     	mTtsConfig = new TtsConfig();
     	
     	// 音频格式
     	mTtsConfig.addParam(TtsConfig.BasicConfig.PARAM_KEY_AUDIO_FORMAT, "pcm16k16bit");
     	mTtsConfig.addParam(TtsConfig.BasicConfig.PARAM_KEY_VOLUME, "9");
     	// 指定语音合成的能力
     	mTtsConfig.addParam(TtsConfig.SessionConfig.PARAM_KEY_CAP_KEY, mCapKey);
     	// 设置合成语速
     	mTtsConfig.addParam(TtsConfig.BasicConfig.PARAM_KEY_SPEED, "5");

        mTtsPlayer = new TTSPlayer();        
        
     	mTtsPlayer.init(ttsInitParam.getStringConfig(), null);
     	if (mTtsPlayer.getPlayerState() == TTSPlayer.PLAYER_STATE_IDLE) {
     		
     		return true;
     	} else {
     		return false;
     	}     	
    }
	// 云端合成,不启用编码传输(默认encode=none)
	public void synth(String text) {	
		if (mTtsPlayer.getPlayerState() == TTSCommonPlayer.PLAYER_STATE_PLAYING
				|| mTtsPlayer.getPlayerState() == TTSCommonPlayer.PLAYER_STATE_PAUSE) {
			mTtsPlayer.stop();
		}

		if (mTtsPlayer.getPlayerState() == TTSCommonPlayer.PLAYER_STATE_IDLE) {
			mTtsPlayer.play(text, mTtsConfig.getStringConfig());
			Log.i(TAG, "Tts context: " + text);
		} else {
			Log.e("TAG", "TtsPlayer is busy");
		}
	}

	public void stopHciTts(){
		if (mTtsPlayer.getPlayerState() == TTSCommonPlayer.PLAYER_STATE_PLAYING//合成中
				|| mTtsPlayer.getPlayerState() == TTSCommonPlayer.PLAYER_STATE_PAUSE) {//暂停中
			mTtsPlayer.stop();
		}
	}
   
    /**
     * Tts的反初始化和系统的反初始化, 在Init方法成功后, 执行结束时需要调用反初始化, 否则会导致引擎没有停止运行, 在下一次运行时会出现返回
     * HCI_ERR_SYS_ALREADY_INIT 或其他错误信息
     */
    public void release() {
        // Tts反初始化
    	if (mTtsPlayer != null) {
			mTtsPlayer.release();
		}
    } 
    
 // 播放器回调
 	private class TTSEventProcess implements TTSPlayerListener {

 		@Override
 		public void onPlayerEventPlayerError(PlayerEvent playerEvent,
 				int errorCode) {
 			Log.i(TAG, "onError " + playerEvent.name() + " code: " + errorCode);
 		}

 		@Override
 		public void onPlayerEventProgressChange(PlayerEvent playerEvent,
 				int start, int end) {
 			Log.i(TAG, "onProcessChange " + playerEvent.name() + " from "
 					+ start + " to " + end);
 		}

 		@Override
 		public void onPlayerEventStateChange(PlayerEvent playerEvent) {
 			Log.i(TAG, "onStateChange " + playerEvent.name()); 			
 			if (playerEvent == PlayerEvent.PLAYER_EVENT_END) {
				Log.i(TAG, "tts play finish");
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}	
				
				Message m = mUIHandle.obtainMessage(1, PublicConstant.HANDLER_TTS_COMPLETE_SUCCESS, 1, null);
				mUIHandle.sendMessage(m);				
 			}else if(playerEvent == PlayerEvent.PLAYER_EVENT_BEGIN){
 				Message m = mUIHandle.obtainMessage(1, PublicConstant.HANDLER_TTS_START, 1, null);
				mUIHandle.sendMessage(m);	
 			}
 		}
 	}

}
